package com.ceiec.base.init;

import com.ceiec.base.event.CommonApplicationEventMulticaster;
import com.ceiec.base.event.ICommonApplicationEventListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Map;

/**
 * desc:
 *
 * @author : ckl
 * creat_date: 2019/11/11 0011
 * creat_time: 15:46
 **/
@Component
@Slf4j
public class InitRunner implements CommandLineRunner,ApplicationContextAware {


    private ApplicationContext applicationContext;

    @Autowired
    private CommonApplicationEventMulticaster commonApplicationEventMulticaster;

    @Override
    public void run(String... args) throws Exception {
        Map<String, ICommonApplicationEventListener> map = applicationContext.getBeansOfType(ICommonApplicationEventListener.class);
        Collection<ICommonApplicationEventListener> listeners = map.values();
        for (ICommonApplicationEventListener listener : listeners) {
            /**
             * 注册事件listener到事件发布器
             */
            log.info("register listener:{}",listener);
            commonApplicationEventMulticaster.addApplicationListener(listener);
        }

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
